using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
//using E = Excel;
using System.Reflection;
using Dimok.Data.Database;
using Dimok.Exceptions;
using Img = Dimok.Images;

/*
Name:String,Type:String - Type:adVarChar,Attrs:104,Size:50
Name:Integer,Type:Int32 - Type:adInteger,Attrs:120,Size:4
Name:Date,Type:DateTime - Type:adDBTimeStamp,Attrs:120,Size:16
Name:Decimal,Type:Decimal - Type:adNumeric,Attrs:120,Size:19
Name:Byte,Type:Byte - Type:adUnsignedTinyInt,Attrs:120,Size:1
Name:Boolean,Type:Boolean - Type:adBoolean,Attrs:120,Size:2
Name:Text,Type:String - Type:adLongVarChar,Attrs:232,Size:2147483647
Name:Image,Type:Byte[] - Type:adLongVarBinary,Attrs:232,Size:2147483647
Name:SmallMone,Type:Decimal - Type:adCurrency,Attrs:120,Size:8
Name:Money,Type:Decimal - Type:adCurrency,Attrs:120,Size:8
Name:Float,Type:Double - Type:adDouble,Attrs:120,Size:8
 
*/
namespace ImageToDisk{
	public class ImageTree{
		public ImageTree(){}
		public static void MakeImageTree(string path,MainForm mainForm){
			//object m = Missing.Value;
			string conn = ConfigurationSettings.AppSettings["conn"];
			string connADO = ConfigurationSettings.AppSettings["connADO"];
			string connImages = ConfigurationSettings.AppSettings["connImages"];
			StreamReader sr = new StreamReader(path);
			var imageDirectory = "Images for "+Path.GetFileNameWithoutExtension(path);
			path = Path.Combine(Path.GetDirectoryName(path),imageDirectory);
			//E.ApplicationClass excel = new E.ApplicationClass();
			//E.Workbook wb = null;
			//wb = (E.Workbook)excel.Workbooks.Open((path,m,m,m,m,m,m,m,m,m,m,m,m);
			//E.Worksheet wsh = (E.Worksheet)wb.Worksheets[1];
			//Excel.Range applID = wsh.get_Range(column+"2",m);
			int count = 0;
			while(sr.Peek()>=0) {
				var line = sr.ReadLine().Trim().Split(',');
				string applID = line[0];
				string companyID = line[1];
				if(applID != "" /*&& int.Parse(applID) != 0*/) {
					count++;
					//DataSet dsAppl = SQLHelperEx.ExecuteDatasetEx(conn, "SELECT FirstName + ' ' + LastName + ' (' + SSN + ')' AS Name FROM  Borrower(@ApplID,0)", applID);
					DataSet dsAppl = SQLHelperEx.ExecuteDatasetEx(conn, 
						"SELECT UsixID AS Name,LoanID FROM  usix.t_CustomerFile_Export WHERE UsixID = @ApplID AND CompanyID_Raw = @CID", applID,companyID);
					var loanId = 0;
					if (!int.TryParse(dsAppl.Tables[0].Rows[0]["LoanID"] + "", out loanId)) {
						mainForm.txtError.Text += "ApplID:" + applID + " has no LoanID" + Environment.NewLine;
						continue;
					}
					string sqlImageTypes = 
						@"SELECT t_Image.ImageTypeID AS FolderID, t_ImageType.ImageType AS FolderName
	FROM  t_Image INNER JOIN t_ImageType ON t_Image.ImageTypeID = t_ImageType.ID
	WHERE (NOT (t_Image.ImageTypeID IN(SELECT value FROM   dbo.registryvalues('FSBImageException') registryvalues))) AND
				(t_Image.LoanID = @ApplID)
	ORDER BY t_Image.LoanID DESC, t_Image.ImageTypeID";
					DataRowCollection drFolderIDs = SQLHelperEx.ExecuteDatasetEx(connImages,sqlImageTypes,loanId).Tables[0].Rows;
					string dir = Path.Combine(path,dsAppl.Tables[0].Rows[0]["Name"].ToString());
					foreach(DataRow row in drFolderIDs){
						string folderPath = Path.Combine(dir,Regex.Replace(row["FolderName"]+"",@"[^\w]","_")+".PDF");
						var folderPath1 = folderPath.Replace(imageDirectory, imageDirectory + "1");
						mainForm.stBar.Text = folderPath;
						System.Windows.Forms.Application.DoEvents();
						try {
							var image = Img.Pages.ImageFolder(connImages, loanId, int.Parse(row["FolderID"].ToString()), Img.PageTypes.PDF);
							if (File.Exists(folderPath1) && new FileInfo(folderPath1).Length == image.Length) continue;
							Directory.CreateDirectory(dir);
							//Img.Pages.ImagePageCount(connImages,int.Parse(applID),int.Parse(row["FolderID"].ToString()));
							SaveBytes(image, folderPath);
						} catch (Exception exc) {
							mainForm.txtError.Text += "***** Folder:" + folderPath + Environment.NewLine + ClientException.GetExceptions(exc);
							System.Windows.Forms.Application.DoEvents();
						}
					}
				}
			}
			mainForm.stBar.Text = "Done with "+path;
		}
		public static void FileToImage(string path, string ext, MainForm mainForm) {
			string conn = ConfigurationSettings.AppSettings["conn"];
			foreach (string fileName in Directory.GetFiles(path, ext)) {
				try {
					string usixID = Path.GetFileNameWithoutExtension(fileName).Substring(0,8);
					string loanID = SQLHelperEx.ExecuteScalarEx(conn, "SELECT LoanID FROM usix.t_CustomerFile_Export WHERE UsixID=@UID",usixID ) + "";
					if (loanID == "") continue;
					mainForm.stBar.Text = "Loan:"+loanID+". "+fileName; System.Windows.Forms.Application.DoEvents();
					Dimok.Images.Pages.ImagePagesInsert(conn, int.Parse(loanID), 1, fileName, -1);
					File.Move(fileName, Path.GetDirectoryName(fileName) + "\\Done\\" + Path.GetFileName(fileName));
				} catch (Exception exc) {
					mainForm.txtError.Text += "***** File:" + fileName + Environment.NewLine + ClientException.GetExceptions(exc);
					System.Windows.Forms.Application.DoEvents();
				}
			}
		}
		private static void SaveBytes(byte[] bytes, string fileName) {
			if (bytes == null) return;
			fileName = fileName.Replace("..", ".");
			FileStream fs = new FileStream(fileName, FileMode.Create);
			fs.Write(bytes, 0, bytes.Length);
			fs.Close();
		}
	}
}
